<template>
    <!-- 数据中心/财务数据中心/收支分类 -->
    <div class="incomeExpend">
        <div class="top_operation">
            <!-- 顶部四级联动选择器联动组件 -->
            <TopSelect
                ref="topSelect"
                @headChange="getHeadId"
                :isRegionShow="isRegionShow"
                @regionChange="getRegionId"
                :isCityShow="isCityShow"
                @cityChange="getCityId"
                :isWareShow="isWareShow"
                @wareChange="getWareId"
            ></TopSelect>
            <div class="every_operation">
                <span>收支项名称：</span>
                <a-input placeholder="请输入收支项名称" v-model="financeName" style="width:195px;" allowClear/>
            </div>
            <div class="every_operation">
                <span>收支类型：</span>
                <a-select style="width: 195px" placeholder="请选择收支类型" @change="handleChange" v-model="financeType" allowClear>
                    <a-select-option value="income">
                        收入
                    </a-select-option>
                    <a-select-option value="pay">
                        支出
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation">
                <span>明细分类：</span>
                <a-select style="width: 195px" placeholder="请选择明细分类" @change="handleChange" v-model="financeDetailType" allowClear>
                    <a-select-option value="operation">
                        运作类
                    </a-select-option>
                    <a-select-option value="fixed">
                        固定类
                    </a-select-option>
                    <a-select-option value="temp">
                        临时类
                    </a-select-option>
                </a-select>
            </div>

            <div class="every_operation">
                <span>创建人：</span>
                <a-input placeholder="请输入创建人" v-model="createBy" style="width:195px;" allowClear/>
            </div>
            <div class="every_operation">
                <span>创建时间：</span>
                <a-range-picker
                    v-model="createTime"
                    :show-time="{ format: 'HH:mm:ss' }"
                    format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="['Start Time', 'End Time']"
                    @change="createChange"
                    @ok="createOk"
                    style="width:195px;"
                />
            </div>
            <div class="every_operation">
                <span>修改人：</span>
                <a-input placeholder="请输入修改人" v-model="updateBy" style="width:195px;" allowClear/>
            </div>
            <div class="every_operation">
                <span>修改时间：</span>
                <a-range-picker
                    v-model="updateTime"
                    :show-time="{ format: 'HH:mm:ss' }"
                    format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="['Start Time', 'End Time']"
                    @change="editChange"
                    @ok="editOk"
                    style="width:195px;"
                />
            </div>

            <div class="button_div">
                <a-button type="primary" icon="search" @click="onSearch()">搜索</a-button>
                <a-button type="primary" icon="sync" style="margin-left:20px;" @click="onReset()">重置</a-button>
            </div>
        </div>
        
        <div class="add_btn">
            <a-button type="primary" icon="plus" @click="showDrawer">新增</a-button>
            <a-button style="margin-left:20px;" v-if="deletdBtnShow" @click="batchDelete()">批量删除</a-button>
            <!-- 右滑抽屉 -->
            <a-drawer
                :title="drawerTitle"
                :placement="placement"
                :closable="false"
                :visible="visible"
                @close="onClose"
                width="500"
            >
                <a-form-model
                    ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                    labelAlign="left"
                >
                    <a-form-model-item ref="financeName" label="收支项名称" prop="financeName">
                        <a-input
                            v-model.trim="form.financeName"
                            placeholder="请输入收支项名称"
                            @blur="() => {$refs.financeName.onFieldBlur()}"
                        />
                    </a-form-model-item>

                    <a-form-model-item label="收支类型" prop="financeType">
                        <a-select v-model="form.financeType" placeholder="请选择收支类型">
                            <a-select-option value="income">
                                收入
                            </a-select-option>
                            <a-select-option value="pay">
                                支出
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>

                    <a-form-model-item label="明细分类" prop="financeDetailType">
                        <a-select v-model="form.financeDetailType" placeholder="请选择明细分类">
                            <a-select-option value="operation">
                                运作类
                            </a-select-option>
                            <a-select-option value="fixed">
                                固定类
                            </a-select-option>
                            <a-select-option value="temp">
                                临时类
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    
                    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
                        <a-button type="primary" @click="onSubmit">
                            确定
                        </a-button>
                        <a-button style="margin-left: 10px;" @click="cancelForm">
                            取消
                        </a-button>
                    </a-form-model-item>
                </a-form-model>
            </a-drawer>
        </div>

        <div class="select_number">
            <span class="number_span">已选择<b>{{selectNumber}}</b>项</span>
            <span class="clear_span" @click="clearSelect">清空</span>
        </div>
        
        <div class="data_source_list">
            <div class="data_source_details">
                <a-table
                    :loading="tableLoading"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                    :columns="columns" 
                    :data-source="data"
                    :pagination="false"
                    bordered
                    rowKey="id"
                    >
                    <span slot="financeName" slot-scope="text, record" href="javascript:;">
                        <a-tooltip placement="top">
                            <template slot="title">
                                <span v-if="record.typeFlag == 'system'"><span style="color:red;padding-right:3px;">*</span>{{text}}</span>
                                <span v-else>{{text}}</span>
                            </template>
                            <span v-if="record.typeFlag == 'system'"><span style="color:red;padding-right:3px;">*</span>{{text}}</span>
                            <span v-else>{{text}}</span>
                        </a-tooltip>
                    </span>

                    <a slot="action" slot-scope="text, record" href="javascript:;">
                        <a-button type="link" style="margin-right:8px;width:50px;height:20px;" @click="editDrawer(record)" v-if="record.typeFlag == 'normal'">修改</a-button>
                        <a-button type="link" style="margin-right:8px;width:50px;height:20px;" @click="editDrawer(record)" v-else disabled>修改</a-button>
                        <a-button type="link" style="margin-left:-16px;width:50px;height:20px;" @click="showModal(record)" v-if="record.typeFlag == 'normal'">删除</a-button>
                        <a-button type="link" style="margin-left:-16px;width:50px;height:20px;" @click="showModal(record)" v-else disabled>删除</a-button>
                    </a>
                </a-table>
                <!-- 确认删除对话框 -->
                <DelModal 
                    :visible="editVisible"
                    @ok="handleOk"
                    @cancel="handleNo"
                />
                <!-- 底部分页组件 -->
                <BottomPagination
                    :total="total"
                    @pageChange="pageChange"
                    @sizeChange="sizeChange"
                ></BottomPagination>
            </div>
            <!-- 批量删除对话框 -->
            <DelModal 
                :visible="batchDeleteVisible"
                :loading="batchDeleteConfirmLoading"
                @ok="batchDeleteHandleOk"
                @cancel="batchDeleteHandleCancel"
            />
        </div>
    </div>
</template>

<script>
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            ellipsis: true,
            width: 80,
            customRender:(text,records,index)=>`${index + 1}`
        },
        {
            title: '收支项名称',
            dataIndex: 'financeName',
            key: 'financeName',
            align: 'center',
            ellipsis: true,
            scopedSlots: { 
                customRender: 'financeName' 
            },
        },
        {
            title: '收支类型',
            dataIndex: 'financeType',
            key: 'financeType',
            align: 'center',
            ellipsis: true,
            width: 120,
            customRender: (text, record, index) => {
                let be = "";
                if (text == 'income') {
                    be = "收入";
                } else {
                    be = "支出";
                } 
                return be;
            }
        },
        {
            title: '明细分类',
            dataIndex: 'financeDetailType',
            key: 'financeDetailType',
            align: 'center',
            ellipsis: true,
            width: 120,
            customRender: (text, record, index) => {
                let be = "";
                if (text == 'operation') {
                    be = "运作类";
                } else if (text == 'fixed') {
                    be = "固定类"
                } else {
                    be = "临时类";
                } 
                return be;
            }
        },
        {
            title: '创建人',
            dataIndex: 'createBy',
            key: 'createBy',
            align: 'center',
            ellipsis: true,
            width: 120,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '修改人',
            dataIndex: 'updateBy',
            key: 'updateBy',
            align: 'center',
            ellipsis: true,
            width: 120,
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            align: 'center',
            ellipsis: true,
        },
        { 
            title: '操作', 
            dataIndex: '', 
            key: 'x', 
            scopedSlots: { 
                customRender: 'action' 
            },
            align: 'center',
            width: 160,
        },
    ];

    import TopSelect from '../../meter/TopSelect'
    import BottomPagination from '../../meter/BottomPagination'
    import DelModal from '../../../components/base/delModal.vue'
    import { getREList, addRE, editRE, deleteRE, getREName, } from '@/api/api'

    export default {
        name: "IncomeExpend",
        components: {
            TopSelect,
            BottomPagination,
            DelModal,  
        },
        data () {
            return {
                financeName: undefined, // 收支项分类名称
                financeType: undefined, // 收支项分类类型
                financeDetailType: undefined, // 明细分类
                data: [],
                columns,
                tableLoading: false,
                selectNumber: 0, // 当前选中数据条数
                selectedRowKeys: [], // 当前选择集合
                deletdBtnShow: false, // 批量删除按钮是否显示
                headquartersId: '', // 总部id
                regionId: '', // 大区id
                cityId: '', // 城市id
                organizeId: '', // 仓库id
                isRegionShow: true,
                isCityShow: true,
                isWareShow: true,
                createBy: undefined, // 创建人
                createTime: [], // 创建时间
                updateBy: undefined, // 修改人
                updateTime: [], // 修改时间
                createTime_begin: '', // 创建时间开始时间
                createTime_end: '', // 创建时间结束时间
                updateTime_begin: '', // 修改时间开始时间
                updateTime_end: '', // 修改时间结束时间
                dateFormat: 'YYYY-MM-DD HH:mm:ss',
                pageNo: 1,
                pageSize: 10,
                total: 0,
                visible: false,
                placement: 'right',
                drawerTitle: '新增收支项',
                labelCol: { span: 7 },  
                wrapperCol: { span: 16 },
                other: '',
                form: {
                    regionId: '',
                    region: '',
                    cityId: '',
                    city: '',
                    organizeId: '',
                    name: '',
                    financeName: '',
                    financeType: '',
                    financeDetailType: '',
                },
                rules: {
                    financeName: [
                        { required: true, message: '请输入收支项名称', trigger: 'blur' },
                    ],
                    financeType: [
                        { required: true, message: '请选择收支类型', trigger: 'change', },
                    ],
                    financeDetailType: [
                        { required: true, message: '请选择明细分类', trigger: 'change', },
                    ],
                },
                validStatus: true, // 当前表单验证状态，true表示成功，false表示失败
                editVisible: false, // 确认删除对话框
                batchDeleteVisible: false, // 批量删除
                batchDeleteConfirmLoading: false,
                nameList: [],
                regionList: [],
                cityList: [],
                warehouseList: [],
                regionName: '', // 大区名称
                cityName: '', // 城市名称
                warehouseName: '', // 仓库名称
                addMode: true,
                disabled: false,
                id: '',
                ids: '',

            }
        },
        created() {
        },
        computed: {
            rowSelection() {
                return {
                    onChange: (selectedRowKeys, selectedRows) => {
                        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                        this.selectedRowKeys = selectedRowKeys
                        this.selectNumber = selectedRowKeys.length
                        if(this.selectedRowKeys.length > 0){
                            this.deletdBtnShow = true
                        }else{
                            this.deletdBtnShow = false
                        }
                    },
                    getCheckboxProps: record => ({
                        props: {
                            disabled: record.typeFlag == 'system',
                        },
                    }),
                };
            },
        },
        methods: {
            // 选择框过滤
            filterOption(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            // 搜索
            onSearch() {
                if( (this.regionId == '' || this.regionId == undefined) || (this.cityId == '' || this.cityId == undefined) || (this.organizeId == '' || this.organizeId == undefined) ){
                    this.$message.warning('搜索时必须先选择大区、城市和仓库！')
                }else{
                    this.pageSize = 10
                    this.pageNo = 1
                    this.getREList()
                }
                this.selectNumber = 0
                this.selectedRowKeys = []
                this.deletdBtnShow = false
            },
            // 重置
            onReset() {
                this.$refs.topSelect.onReset()
                this.financeName = undefined
                this.financeType = undefined
                this.financeDetailType = undefined
                this.createBy = ''
                this.createTime = []
                this.updateBy = ''
                this.updateTime = []
                this.createTime_begin = ''
                this.createTime_end = ''
                this.updateTime_begin = ''
                this.updateTime_end = ''
                this.pageSize = 10
                this.pageNo = 1
                this.total = 0
                this.data = []
                this.selectNumber = 0
                this.selectedRowKeys = []
                this.deletdBtnShow = false
            },
            // 获取列表数据
            getREList() {
                let params = {
                    regionId: this.regionId,
                    cityId: this.cityId,
                    organizeId: this.organizeId,
                    financeName: this.financeName,
                    financeType: this.financeType,
                    financeDetailType: this.financeDetailType,
                    createBy: this.createBy,
                    updateBy: this.updateBy,
                    createTime_begin: this.createTime_begin,
                    createTime_end: this.createTime_end,
                    updateTime_begin: this.updateTime_begin,
                    updateTime_end: this.updateTime_end,
                    pageSize: this.pageSize,
                    pageNo: this.pageNo,
                    delFlag: 0,
                }
                this.tableLoading = true
                getREList(params).then((res)=>{
                    this.tableLoading = false
                    if(res.success){
                        this.data = res.result.records
                        this.total = res.result.total
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            },
            
            handleChange(value) {
                console.log(`selected ${value}`);
            },
            // 选中
            onSelectChange(selectedRowKeys) {
                this.selectedRowKeys = selectedRowKeys
                this.selectNumber = selectedRowKeys.length
                if(this.selectedRowKeys.length > 0){
                    this.deletdBtnShow = true
                }else{
                    this.deletdBtnShow = false
                }
            },
            // 清空选中
            clearSelect() {
                this.selectNumber = 0
                this.selectedRowKeys = []
                this.deletdBtnShow = false
            },
            // 获取当前总部id
            getHeadId(data) {
                this.headquartersId = data
            },
            // 获取当前大区id
            getRegionId(data, name) {
                this.regionId = data
                this.form.regionId = data
                this.form.region = name
                this.$refs.topSelect.clearRegion()
            },
            // 获取当前城市id
            getCityId(data, name) {
                this.cityId = data
                this.form.cityId = data
                this.form.city = name
                this.$refs.topSelect.clearCity()
            },
            // 获取当前仓库id
            getWareId(data, name) {
                this.organizeId = data
                this.form.organizeId = data
                this.form.name = name
            },
            // 获取当前页数、条数
            pageChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.getREList()
            },
            // 获取当前页数、条数
            sizeChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.getREList()
            },
            // 创建时间
            createChange(value, dateString) {
                this.createTime = value
                this.createTime_begin = dateString[0]
                this.createTime_end = dateString[1]
            },
            createOk(value) {
                console.log('onOk: ', value);
            },
            // 修改时间
            editChange(value, dateString) {
                this.updateTime = value
                this.updateTime_begin = dateString[0]
                this.updateTime_end = dateString[1]
            },
            editOk(value) {
                console.log('onOk: ', value);
            },
            // 新增收支项
            showDrawer() {
                if( (this.regionId == '' || this.regionId == undefined) || (this.cityId == '' || this.cityId == undefined) || (this.organizeId == '' || this.organizeId == undefined) ){
                    this.$message.warning('新增时必须先选择大区、城市和仓库！')
                    return
                }

                this.visible = true;
                this.drawerTitle = '新增收支项分类'
                this.addMode =true
                this.disabled = false
                this.form.financeName = ''
                this.form.financeType = undefined
                this.form.financeDetailType = undefined
                // 只有验证失败，新增的时候才重置验证状态
                if(this.validStatus === false) {
                    this.$refs.ruleForm.resetFields()
                }

            },
            onClose() {
                this.visible = false;
            },
            // 修改收支项
            editDrawer(record) {
                this.visible = true;
                this.drawerTitle = '修改收支项分类'
                this.addMode =false
                this.disabled = true
                this.form.region = record.region
                this.form.city = record.city
                this.form.name = record.name
                this.form.financeName = record.financeName
                this.form.financeType = record.financeType
                this.form.financeDetailType = record.financeDetailType
                this.id = record.id
            },
            // 表单
            onSubmit() {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        this.validStatus = true
                        if(this.addMode){ // 新增
                            let params = {
                                region: this.form.region,
                                city: this.form.city,
                                name: this.form.name,
                                regionId: this.form.regionId,
                                cityId: this.form.cityId,
                                organizeId: this.form.organizeId,
                                financeName: this.form.financeName,
                                financeType: this.form.financeType,
                                financeDetailType: this.form.financeDetailType,
                            }
                            addRE(params).then((res)=>{
                                if(res.success){
                                    this.visible = false
                                    if( this.regionId != '' && this.cityId != '' && this.organizeId != '' ){
                                        this.getREList()
                                    }
                                }else{
                                    this.$message.warning(res.message)
                                }
                            })
                        }else{ // 修改
                            let params = {
                                id: this.id,
                                financeName: this.form.financeName,
                                financeType: this.form.financeType,
                                financeDetailType: this.form.financeDetailType,
                            }
                            editRE(params).then((res)=>{
                                if(res.success){
                                    this.visible = false
                                    this.getREList()
                                }else{
                                    this.$message.warning(res.message)
                                }
                            })
                        }
                    } else {
                        this.validStatus = false
                        return false;
                    }
                });
                },
            cancelForm() {
                this.visible = false;
            },
            // 确认删除对话框
            showModal(record) {
                this.editVisible = true;
                this.ids = record.id
            },
            handleOk(e) {
                this.editVisible = false;
                let params = {
                    ids: this.ids,
                }
                deleteRE(params).then((res)=>{
                    if(res.success){
                        this.visible = false
                        this.getREList()
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            },
            handleNo(){
                this.editVisible = false
            },
            // 批量删除
            batchDelete() {
                this.batchDeleteVisible = true
                this.ids = this.selectedRowKeys.join(',')
            },
            batchDeleteHandleOk(e) {
                this.batchDeleteConfirmLoading = true;
                let params = {
                    ids: this.ids,
                }
                deleteRE(params).then((res)=>{
                    this.batchDeleteConfirmLoading = false;
                    if(res.success){
                        this.batchDeleteVisible = false;
                        this.selectNumber = 0
                        this.selectedRowKeys = []
                        this.deletdBtnShow = false
                        this.getREList()
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            },
            batchDeleteHandleCancel(e) {
                this.batchDeleteVisible = false;
            },

        },
        
    }
</script>

<style lang="less" scoped>
    .incomeExpend{
        width: 100%;
        padding: 0 10px 10px 10px;
        font-style: Microsoft YaHei;
        background: #ffffff;
        box-sizing: border-box;
        .top_operation{
            margin-bottom: 10px;
            overflow: hidden;
            .every_operation{
                float: left;
                margin-top: 10px;
                margin-right: 20px;
                span{
                    display: inline-block;
                    width: 85px;
                }
            }
            .button_div{
                float: left;
                margin-top: 10px;
            }
        }
        .select_number{
            width: 100%;
            height: 36px;
            padding-left: 20px;
            margin-bottom: 10px;
            box-sizing: border-box;
            background: rgba(57, 72, 103, .22);
            line-height: 36px;
            .number_span{
                color: #ffffff;
                margin-right: 30px;
                b{
                    color: #394867;
                    margin: 0 15px;
                }
            }
            .clear_span{
                cursor: pointer;
                color: #394867;
            }
        }
        .add_btn{
            margin-bottom: 10px;
        }
        .data_source_list{
            h3{
                font-weight: bold;
            }
            .data_pagination{
                width: 100%;
                height: 32px;
                margin: 20px 0 10px 0;
            }
        }
    }
</style>